package cn.lanqiao.springbootproject.service;

import cn.lanqiao.springbootproject.mapper.ArticleMapper;
import cn.lanqiao.springbootproject.vo.ArticleVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;

@Service
public class ArticleService {

    @Autowired
    ArticleMapper articleMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Value("${article.like.key}")
    String ARTICLE_LIKE_COUNT_KEY ;

    @Value("${article.like.id}")
    String ARTICLE_LIKE_ID;

    public List<ArticleVO> queryByPage() {
        return articleMapper.queryByPage();
    }

    /**
     * 点赞
     */
    @Transactional
    public void likeArticle(int userId, int articleId) throws Exception {
        //验证redis中是否存在articleId
        validateArticle(articleId);
        //更新文章总点赞数
        redisTemplate.opsForHash().increment(ARTICLE_LIKE_COUNT_KEY, ARTICLE_LIKE_ID + ":" + articleId, 1);
        //更新articleId:userIdSet

        //更新userId:articleIdSet

    }

    /**
     * 取消点赞
     */
    @Transactional
    public void unlikeArticle(int userId, int articleId){
        //验证redis中是否存在articleId

        //更新文章总点赞数
        redisTemplate.opsForHash().increment(ARTICLE_LIKE_COUNT_KEY, ARTICLE_LIKE_ID + ":" + articleId, -1);
        //更新articleId:userIdSet

        //更新userId:articleIdSet

    }

    @Transactional
    public void validateArticle(int articleId) throws RuntimeException {
        Integer count = (Integer) redisTemplate.opsForHash().get(ARTICLE_LIKE_COUNT_KEY,ARTICLE_LIKE_ID + ":" + articleId);
        if(count == null){
            //通过articleId获得文章点赞数
            ArticleVO articleVO = articleMapper.getById(articleId);
            if(articleVO == null)
                throw new RuntimeException("该文章不存在！");
            //添加进redis总数
            redisTemplate.opsForHash().put(ARTICLE_LIKE_COUNT_KEY, ARTICLE_LIKE_ID + ":" + articleId, articleVO.getTotalLikeCount());
            //添加进redis中article -> userSet
            redisTemplate.opsForValue().set(ARTICLE_LIKE_ID + ":" + articleId,new HashSet<>());
        }
    }
}
